﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CreatObject : MonoBehaviour
{

    [SerializeField]
    int hor, ver, space;
    [SerializeField]
    Material mat;
    

    [ContextMenu("Creat")]

    public void CreatSphere()
    {

        int count = transform.childCount;
        for (int i = 0; i < count; i++)
        {
            DestroyImmediate(transform.GetChild(0).gameObject);
        }

        for (int y = 0; y < hor; y++)
        {
            for (int x = 0; x < ver; x++)
            {
                GameObject o = GameObject.CreatePrimitive(PrimitiveType.Sphere);
                o.transform.parent = this.transform;
                o.transform.localPosition = new Vector3(x + x * space, 0, y + y * space);
                o.GetComponent<MeshRenderer>().material = mat;

            }
        }

        CenterPos();
    }

    private void CenterPos()
    {
        var center = Vector3.zero;
        for(int i = 0; i<transform.childCount;i++)
        {
            center += transform.GetChild(i).localPosition;
        }
        center /= transform.childCount;
        for (int i = 0; i < transform.childCount; i++)
        {
            transform.GetChild(i).localPosition -= center;
        }
    }
} 
